package org.lex.net.ftp.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.lex.io.filesystem.FileNameUtilities;
import org.lex.net.ftp.IFTPFile;


/**
 * ���д�InputStream����"LIST"����ص��ļ��б� ��ÿ�л�Ӧ�н�����FtpFile
 */
public class FileListParser {
	public static List<IFTPFile> parse(InputStream in, String pwd, Charset charset) throws IOException {
		return parse(in, pwd, charset, FTPFileParserFactory.getDefaultFactory().getParser());
	}

	public static List<IFTPFile> parse(InputStream in, String pwd, Charset charset, FTPFileParser parser) throws IOException {
		String parent = FileNameUtilities.getStandardPath(pwd, '/');
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset), 1024);
		ArrayList<IFTPFile> list = new ArrayList<IFTPFile>(20);
		while (true) {
			String line = reader.readLine();
			if (null == line || 0 == line.length())
				break;
			IFTPFile file = parser.parse(line);
			if (null == file)
				continue;
			file.setDirectory(parent);
			list.add(file);
		}
		return list;
	}
}
